<!-- 编辑个人信息 -->
<script setup lang="ts">
import { useUserInfoStore } from '@/store/userInfo'
import avatarPlaceholder from '@/static/images/profile/avatar_placeholder.png'
import { uploadFileAPI } from '@/apis/uploadFile'
import { updateProfileAPI } from '@/apis/uploadProfile'
import { useGeneralDataStore } from '@/store/generalData'

const router = useRouter()
const userInfoStore = useUserInfoStore()
const generalDataStore = useGeneralDataStore()

// 表单数据
const formData = ref({
  avatar: '',
  username: '',
  company: '',
  company_type: '',
  duties: '',
})

// 校验规则
const rules = {
  avatar: [
    { required: true, message: '头像不可为空', trigger: ['blur', 'change'] },
  ],
  username: [
    { required: true, message: '姓名不可为空', trigger: ['blur', 'change'] },
  ],
  company: [
    { required: true, message: '单位不可为空', trigger: ['blur', 'change'] },
  ],
  company_type: [
    { required: true, message: '单位类型不可为空', trigger: ['blur', 'change'] },
  ],
  duties: [
    { required: true, message: '职务不可为空', trigger: ['blur', 'change'] },
  ],
}

// 表单组件饮用
const formRef = ref<any>(null)
// 是否处于加载中状态
const loading = ref(false)
// 是否显示提交成功弹窗
const isShowSuccessModal = ref(false)

onLoad(() => {
  formData.value.avatar = userInfoStore.userInfo?.avatar || ''
  formData.value.username = userInfoStore.userInfo?.username || ''
  formData.value.company = userInfoStore.userInfo?.company || ''
  formData.value.company_type = userInfoStore.userInfo?.company_type || ''
  formData.value.duties = userInfoStore.userInfo?.duties || ''
})

/* ------------------------------- 选择头像 START ------------------------------- */
const handleChooseAvatar = useThrottleFn(async (e: any) => {
  const url = e.detail.avatarUrl
  try {
    const res = await uploadFileAPI({
      tempFilePath: url,
      fileType: 'image',
    }, userInfoStore.userInfo!.token!)

    if (res.data) {
      const resData = JSON.parse(res.data)
      formData.value.avatar = resData.data.fullurl
    }
    else {
      uni.showToast({ title: '上传失败，请稍后重试', icon: 'none' })
    }
  }
  catch (err) {
    uni.showToast({ title: JSON.stringify(err), icon: 'none' })
  }
}, 1000)
/* -------------------------------- 选择头像 END -------------------------------- */

/* ------------------------------ 选择单位类型 START ------------------------------ */
const selectedCompanyTypeIndex = ref(0)
const companyTypes = computed(() => {
  const val = ref<string[]>([])
  if (generalDataStore.generalData?.company_type) {
    Object.keys(generalDataStore.generalData?.company_type).forEach((key: string) => {
      val.value.push(generalDataStore.generalData?.company_type[key])
    })
  }
  return val
})

function handleSelectCompanyType(e: any) {
  const index = Number(e.detail.value) + 1
  formData.value.company_type = generalDataStore.generalData?.company_type[index.toString()] || ''
  selectedCompanyTypeIndex.value = e.detail.value
}
/* ------------------------------- 选择单位类型 END ------------------------------- */

/**
 * @description 提交表单时触发
 */
const handleSubmit = useThrottleFn(() => {
  if (userInfoStore.userInfo && userInfoStore.userInfo.token) {
    formRef.value.validate()
      .then(async () => {
        // 控制加载状态
        loading.value = true

        try {
          const res = await updateProfileAPI(
            formData.value,
            userInfoStore.userInfo!.token,
          )
          if (res.data?.code === 1) {
            userInfoStore.setUserInfo({
              ...userInfoStore.userInfo!,
              ...formData.value,
            })
            isShowSuccessModal.value = true
          }
          else { uni.showToast({ title: res.data?.msg, icon: 'none' }) }
        }
        catch (err) {
          uni.showToast({ title: '提交失败，请重试', icon: 'none' })
        }
      })
      .catch((errors: AnyObject[]) => {
        // 表单验证失败
        if (errors.length > 0)
          uni.showToast({ title: errors[0].message, icon: 'none' })
      })
  }
  else {
    uni.showToast({ title: '提交失败，请重试', icon: 'none' })
  }
})

/**
 * @description 提交成功，退出页面
 */
function handleExit() {
  router.back()
}
</script>

<template>
  <view class="min-h-screen bg-white">
    <uv-form ref="formRef" :model="formData" :rules="rules">
      <Divider width="720" color="#E6E6E6" />
      <uv-form-item prop="avatar" :custom-style="{ padding: 0, margin: 0 }">
        <button open-type="chooseAvatar" :style="{ backgroundColor: 'transparent' }" @chooseavatar="handleChooseAvatar">
          <ListCell label="头像" height="172">
            <view class="flex items-center">
              <image class="h-100rpx w-100rpx rounded-full" :src="formData.avatar || avatarPlaceholder" />
              <Spacer width="20" />
              <image class="h-24rpx w-16rpx" src="@/static/images/profile/cheveron_right.png" />
            </view>
          </ListCell>
        </button>
      </uv-form-item>
      <Divider width="700" color="#E6E6E6" />
      <uv-form-item prop="username" :custom-style="{ padding: 0, margin: 0 }">
        <ListCell label="姓名">
          <ListInput v-model="formData.username" placeholder="请输入您的姓名" />
        </ListCell>
      </uv-form-item>
      <Divider width="700" color="#E6E6E6" />
      <uv-form-item prop="company" :custom-style="{ padding: 0, margin: 0 }">
        <ListCell label="单位">
          <ListInput v-model="formData.company" placeholder="请输入您的单位" />
        </ListCell>
      </uv-form-item>
      <Divider width="700" color="#E6E6E6" />
      <uv-form-item prop="company_type" :custom-style="{ padding: 0, margin: 0 }">
        <picker
          mode="selector" :value="selectedCompanyTypeIndex" :range="companyTypes"
          @change="handleSelectCompanyType"
        >
          <ListCell label="单位类型">
            <ListLink :value="formData.company_type" placeholder="请选择您的单位类型" />
          </ListCell>
        </picker>
      </uv-form-item>
      <Divider width="700" color="#E6E6E6" />
      <uv-form-item prop="duties" :custom-style="{ padding: 0, margin: 0 }">
        <ListCell label="职务">
          <ListInput v-model="formData.duties" placeholder="请输入您的职务" />
        </ListCell>
      </uv-form-item>
      <Divider width="700" color="#E6E6E6" />
      <ListCell label="电话">
        <view class="text-30rpx text-#999999 leading-42rpx">
          {{ userInfoStore.userInfo?.mobile || '未知' }}
        </view>
      </ListCell>
      <Divider width="700" color="#E6E6E6" />

      <button
        class="fixed bottom-80rpx h-100rpx w-650rpx flex items-center justify-center rounded-full bg-#0037AE text-30rpx text-white font-medium leading-30rpx x-center"
        hover-class="bg-#3266D9"
        @tap="handleSubmit"
      >
        保存修改
      </button>
    </uv-form>
  </view>

  <uv-overlay :show="isShowSuccessModal" @tap="isShowSuccessModal = false">
    <uv-transition mode="zoom-in" :show="isShowSuccessModal">
      <view class="relative h-screen w-screen">
        <view class="absolute left-50% top-50% -translate-50%">
          <Dialog
            :show-cancel-button="false"
            title="提交成功"
            content=""
            confirm-label="确定"
            @cancel="isShowSuccessModal = false"
            @confirm="handleExit"
          />
        </view>
      </view>
    </uv-transition>
  </uv-overlay>
</template>

<route lang="yaml">
name: 'profileSettings'
style:
  navigationBarTitleText: '编辑个人信息'
layout: 'custom'
</route>
